#include "PktReader.h"

TcpdumpHeader aTcpdumpHeader;
PacketHeader aPacketHeader;

PktReader::PktReader()
{}

int PktReader::setCurFp(FILE* fp)
{
	curFp = fp;

	if(0 > newFileInit())
	{
		printf("Error: New File Init Fail!\n");
		return -1;
	}

	return 0;
}

int PktReader::readPkt(Packet* pkt)
{
	if(0 >= fread(&aPacketHeader, 1, sizeof(PacketHeader), curFp))
	{
		return -1;
	}
	if(MAX_PKT_BUFFER_SIZE >= aPacketHeader.savedLength)
	{
		pkt->pktTimeS = aPacketHeader.timeS;
		pkt->pktTimeMs = aPacketHeader.timsMs;
		pkt->pktLength = aPacketHeader.savedLength;
		fread(pkt->rawPkt, 1, aPacketHeader.savedLength, curFp);
		pkt->parsePos = 0;
		pkt->state = DEFAULT_PKT_STATE;
	}
	else
	{
		//Packet Overlength
		fseek(curFp, aPacketHeader.savedLength, SEEK_CUR);
		return 1;
	}

	return 0;
}

int PktReader::newFileInit()
{
	//Just Process Tcpdump Format For Now
	if(0 >= fread(&aTcpdumpHeader, 1, sizeof(TcpdumpHeader), curFp))
	{
		return -1;
	}
	if(aTcpdumpHeader.tcpdumpFlag != ntohl(0xD4C3B2A1))
	{
		printf("Error: Not a Tcpdump Format File!\n");
		return -1;
	}

	return 0;
}
